# -*- coding:utf-8 -*-
import igraph as ig


class LayoutAlgorithmBase(object):
    def __init__(self, algorithm_name):
        self.name = algorithm_name


class LayoutAlgorithmIGraph(LayoutAlgorithmBase):

    def __init__(self, directed=False):
        super().__init__('igraph')
        self.directed = directed

    def execute(self, network):
        # get tuples of edges between nodes position, example:
        # [ (0,1) ]
        nodes_for_graph = list(set(e["source"] for e in network['edges']) | set(e["target"] for e in network['edges']))
        edges_for_graph = [(nodes_for_graph.index(e['source']), nodes_for_graph.index(e['target'])) for e in network['edges']]

        assert(len(network["nodes"]) == len(nodes_for_graph))
        assert(len(network["edges"]) == len(edges_for_graph))

        G = ig.Graph(edges_for_graph, directed=False)
        layt = G.layout("kk", dim=3)
        layt.center()

        nodes = network['nodes']
        for i, dimention in enumerate(layt):
            index = nodes_for_graph[i]
            nodes[index]["location"] = [j*15 for j in dimention]

    def execute_vad(self, network):
        nodes_for_graph = list(set(e["source"] for e in network['edges']) | set(e["target"] for e in network['edges']))
        edges_for_graph = [(nodes_for_graph.index(e['source']), nodes_for_graph.index(e['target'])) for e in network['edges']]

        assert(len(network["nodes"]) == len(nodes_for_graph))
        assert(len(network["edges"]) == len(edges_for_graph))

        rt = []
        rt.append(edges_for_graph[0][0])

        G = ig.Graph(edges_for_graph, directed=False)
        layt = G.layout_reingold_tilford(mode="in", root=rt)
        layt.center()

        nodes = network['nodes']
        for i, dimention in enumerate(layt):
            index = nodes_for_graph[i]
            nodes[index]["location"] = [j*200 for j in dimention]
            tmp = nodes[index]["location"][0]
            nodes[index]["location"][0] = nodes[index]["location"][1]
            nodes[index]["location"][1] = tmp
        
